import { useRouter } from 'vue-router'
import axios from 'axios'
import showMsg from './showMsg'
import { removeLogin } from './auth'

export default async function fetchCoin(part = '') {
  const router = useRouter()
  const token = localStorage.getItem('token')
  if (!token) {
    showMsg({
      type: 'error',
      msg: '登录过期，请重新登录',
      duration: 1000,
      onClose: () => {
        removeLogin()
        router.push('/login')
      }
    })
  } else {
    try {
      const response = await axios.get('/api/north/record/fraction', {
        headers: {
          Authorization: `${token}`
        },
        params: {
          part: part === '' ? '' : part
        }
      })
      const { code } = response.data
      if (code === 200) {
        const { data: coins } = response.data
        return coins
      } else if (code === 401) {
        showMsg({
          type: 'error',
          msg: '登录过期，请重新登录',
          duration: 1000,
          onClose: () => {
            removeLogin()
            router.push('/login')
          }
        })
      } else {
        throw new Error('网络错误，请稍后重试')
      }
    } catch (e) {
      console.log(e)
      showMsg({
        type: 'error',
        msg: '网络错误，请稍后重试',
        duration: 1000
      })
    }
  }
}
